import { ref } from "vue";
import { useCrudForm } from "@/composables/useCrudForm";
import { recruitPublishZpfbFormConfig } from "../form-config";
import { formatDateTime } from "@/utils/xenUtils";
import SysHrRecruitPublishRequestBillZpfbApi from "../api/index";
import commonApi from "@/api/common";
import type {
  ISysHrRecruitPublishRequestBill,
  ISysHrRecruitPublishRequestBillVm,
} from "../api/interface";

/**
 * 招聘发布申请信息专用 Composable
 */
export function useRecruitPublishZpfbInfo() {
  // 创建API实例
  const api = SysHrRecruitPublishRequestBillZpfbApi();

  // API配置
  const apiConfig = {
    search: api.search,
    get: api.get,
    add: api.add,
    edit: api.edit,
    delete: api.delete,
  };

  // 选项数据加载器
  const optionLoaders = {
    group: async (): Promise<{ Value: string; Text: string; }[]> => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetParentsTree();
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
    company: async (): Promise<{ Value: string; Text: string; }[]> => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetUserCompanies();
      // 直接返回公司列表接口的数据
      return result;
    },
  };

  // 使用通用CRUD表单
  const crudForm = useCrudForm<ISysHrRecruitPublishRequestBill, ISysHrRecruitPublishRequestBillVm>(
    recruitPublishZpfbFormConfig,
    apiConfig,
    optionLoaders
  );

  // 初始化时设置公司字段默认值
  crudForm.formData.company = '';

  /**
   * 字段映射配置（API字段路径到表单字段的映射）
   */
  const fieldMapping = {
    // 流程信息
    approver: "Approver",
    approvalTime: "ApprovalTime",

    // 单据信息
    billCode: "BillCode",
    billStatus: "BillStatus",
    workflowStatus: "WorkflowStatus",
    remark: "Remark",

    // 基本信息
    jobPosition: "Title", // 映射到招聘标题
    title: "Title",
    description: "Description",

    // 招聘信息
    hireNumber: "HireNumber",
    expectedDate: "ExpectedDate",

    // 岗位信息
    educationRequirement: "EducationRequirement",
    majorRequirement: "MajorRequirement",
    genderRequirement: "GenderRequirement",
    ageRequirement: "AgeRequirement",
    jobRequirement: "JobRequirement",
    otherRequirement: "OtherRequirement",

    // 待遇信息
    salaryRange: "SalaryRange",
    benefits: "Benefits",

    // 发布信息
    publishStartDate: "PublishStartDate",
    publishEndDate: "PublishEndDate",
    isExternalPublish: "IsExternalPublish",

    // 联系信息
    contactPerson: "ContactPerson",
    contactPhone: "ContactPhone",
    contactEmail: "ContactEmail",

    // 工作信息
    company: "Org.OrgName", // 映射到公司名称
    group: "Group.GroupName", // 映射到部门名称
  };

  /**
   * 加载招聘发布申请详情数据
   */
  const loadRecruitPublishZpfbDetail = async (id: string): Promise<{ success: boolean; isMyApprove?: boolean }> => {
    try {
      // 直接调用API获取完整响应
      const response = await api.get(id);

      if (response && response.Entity) {
        const detail = response.Entity;

        // 设置原始数据
        crudForm.originalData.value = detail;

        // 检查原始数据中的日期字段
        const dateFields = ["ApprovalTime", "ExpectedDate", "PublishStartDate", "PublishEndDate"];
        dateFields.forEach(field => {
          if ((detail as any)[field]) {
            // 日期字段处理（保留用于可能的格式化需求）
          }
        });

        // 先使用通用转换
        crudForm.convertApiDataToFormData(detail, fieldMapping);

        // 添加特殊处理，确保选择器字段正确映射
        await ensurePickerFieldsMapping(detail);

        return {
          success: true,
          isMyApprove: response.IsMyApprove || false
        };
      }
      return { success: false };
    } catch (error) {
      console.error("获取招聘发布申请详情失败:", error);
      return { success: false };
    }
  };

  /**
   * 确保选择器字段正确映射
   */
  const ensurePickerFieldsMapping = async (apiData: any) => {
    // 处理公司 - 通过详情接口的OrgId匹配公司列表的Value，显示对应的Text
    if (apiData.OrgId) {
      // 优先从已缓存的选项数据中查找
      if (recruitPublishZpfbFormConfig.company?.optionsData) {
        const companyOption = recruitPublishZpfbFormConfig.company.optionsData.find(
          (item: any) => item.value === apiData.OrgId
        );
        if (companyOption) {
          crudForm.formData.company = companyOption.text;
          crudForm.pickerValues.company = companyOption.value;
          // 同时设置到 originalData 中，以便 XenDynamicDetailsCard 组件能显示
          if (crudForm.originalData.value && crudForm.originalData.value.Org) {
            crudForm.originalData.value.Org.OrgName = companyOption.text;
          }
          return; // 找到就直接返回
        }
      }

      // 如果缓存中没找到，重新调用公司接口
      const commonApiInstance = commonApi();
      try {
        const companies = await commonApiInstance.GetUserCompanies();
        const companyOption = companies.find((item: any) => item.Value === apiData.OrgId);

        if (companyOption) {
          crudForm.formData.company = companyOption.Text;
          crudForm.pickerValues.company = companyOption.Value;
          // 同时设置到 originalData 中，以便 XenDynamicDetailsCard 组件能显示
          if (crudForm.originalData.value) {
            if (!crudForm.originalData.value.Org) {
              crudForm.originalData.value.Org = {} as any;
            }
            crudForm.originalData.value.Org.OrgName = companyOption.Text;
          }
        }
      } catch (error) {
        console.error('重新加载公司数据失败:', error);
      }
    }

    // 处理部门
    if (apiData.GroupId && recruitPublishZpfbFormConfig.group?.optionsData) {
      const groupOption = recruitPublishZpfbFormConfig.group.optionsData.find(
        (item: any) => item.value === apiData.GroupId
      );
      if (groupOption) {
        crudForm.formData.group = groupOption.text;
        crudForm.pickerValues.group = groupOption.value;
      }
    }

    // 处理单据状态显示
    if (apiData.BillStatus !== undefined) {
      crudForm.formData.billStatus = apiData.BillStatus || "";
    }

    // 处理工作流状态显示
    if (apiData.WorkflowStatus !== undefined) {
      crudForm.formData.workflowStatus = apiData.WorkflowStatus || "";
    }

    // 处理审批时间格式化
    if (apiData.ApprovalTime) {
      crudForm.formData.approvalTime = formatDateTime(apiData.ApprovalTime);
    }

    // 处理预期到岗时间格式化
    if (apiData.ExpectedDate) {
      const formattedDateTime = formatDateTime(apiData.ExpectedDate);
      crudForm.formData.expectedDate = formattedDateTime ? formattedDateTime.split(' ')[0] : "";
    }

    // 处理发布开始时间格式化
    if (apiData.PublishStartDate) {
      const formattedDateTime = formatDateTime(apiData.PublishStartDate);
      crudForm.formData.publishStartDate = formattedDateTime ? formattedDateTime.split(' ')[0] : "";
    }

    // 处理发布结束时间格式化
    if (apiData.PublishEndDate) {
      const formattedDateTime = formatDateTime(apiData.PublishEndDate);
      crudForm.formData.publishEndDate = formattedDateTime ? formattedDateTime.split(' ')[0] : "";
    }

    // 处理是否对外发布显示 - 现在由 formatter 函数处理
    // if (apiData.IsExternalPublish !== undefined) {
    //   crudForm.formData.isExternalPublish = apiData.IsExternalPublish ? "是" : "否";
    // }
  };

  return {
    // 继承通用CRUD表单的所有功能
    ...crudForm,

    // 招聘发布申请信息专用方法
    loadRecruitPublishZpfbDetail,

    // 字段映射
    fieldMapping,
  };
}
